/*
 * Application.cpp
 *
 *  Created on: 26 mars 2009
 *      Author: CHETIER
 */

#include "SnowApplication.h"

/**
 * Default constructor
 */
SnowApplication::SnowApplication()
{
	//Private properties initialization
	_appExit = false;
	_fpsManager = new FPSmanager();
}

/**
 * Destructor
 */
SnowApplication::~SnowApplication()
{
	//delete properties
	SDL_FreeSurface(_screen);
	delete _fpsManager;

	//delete background
	for (list<Cloud*>::iterator i = _background->list_cloud->begin(); i
			!= _background->list_cloud->end(); ++i)
		delete (*i);

	delete _background->list_cloud, _background->list_cloud = NULL;
	SDL_FreeSurface(_background->srf_background);
	SDL_FreeSurface(_background->srf_mask);
	delete _background;
}

///**
// * Initialize the application
// */
int SnowApplication::appInitialize(int pScreenWidth, int pSCreenHeight,
		int pScreenBits)
{
	cout << "  Initializing SDL" << endl;
	if (SDL_Init(SDL_INIT_VIDEO) == -1)
	{
		cout << "  Cannot initialize SDL: " << SDL_GetError() << endl;
		return EXIT_FAILURE;
	}

	cout << "  Initializing frame-rate manager" << endl;
	SDL_setFramerate(_fpsManager, 25);

	cout << "  Initializing exit function" << endl;
	atexit(SDL_Quit);

	cout << "  Initializing video mode" << endl;
	_screen = SDL_SetVideoMode(pScreenWidth, pSCreenHeight, pScreenBits,
			VIDEO_MODE);

	if (_screen == NULL)
	{
		cout << "  Can't set video mode: " << SDL_GetError() << endl;
		return EXIT_FAILURE;
	}

	cout << "  Initializing background" << endl;
	SDL_Surface *srf_buffer = SDL_LoadBMP("bitmaps/landscape.bmp");
	_background = new background();
	_background->list_cloud = new list<Cloud*> ();
	if (srf_buffer == NULL)
	{
		cout << "Error while loading: " << "bitmaps/landscape.bmp";
		return EXIT_FAILURE;
	}
	_background->srf_background = SDL_DisplayFormat(srf_buffer);
	SDL_FreeSurface(srf_buffer), srf_buffer = NULL;

	//Create clouds
	for(int i=0; i<CLOUD_NB; i++)
	{
		Cloud *vCloud = new Cloud("bitmaps/cloud1.bmp", CLOUD_YMAX, CLOUD_YMIN, CLOUD_VELOCITYMAX, _screen->w);
		vCloud->initialize();
		_background->list_cloud->push_back(vCloud);
	}

	return EXIT_SUCCESS;
}

/**
 *
 */
int SnowApplication::appLaunch()
{
	SDL_setFramerate(_fpsManager, FRAMES_PER_SECOND);
	while (!_appExit)
	{
		handleInput();
		think();
		drawFrame();

		//Wait for next frame
		SDL_framerateDelay(_fpsManager);
	}

	return EXIT_SUCCESS;
}

